package org.spiderflow.core.executor.shape;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderflow.common.context.SpiderContext;
import org.spiderflow.core.Spider;
import org.spiderflow.core.model.SpiderFlow;
import org.spiderflow.core.service.SpiderFlowService;
import org.spiderflow.core.utils.SpiderFlowUtils;
import org.spiderflow.common.executor.ShapeExecutor;
import org.spiderflow.common.model.SpiderNode;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 子流程执行器
 *
 * @author Administrator
 */
@Component
public class ProcessExecutor implements ShapeExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessExecutor.class);
    private static final String FLOW_ID = "flowId";
    private final SpiderFlowService spiderFlowService;
    private final Spider spider;

    public ProcessExecutor(SpiderFlowService spiderFlowService, Spider spider) {
        this.spiderFlowService = spiderFlowService;
        this.spider = spider;
    }

    @Override
    public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
        String flowId = node.getStringJsonValue(FLOW_ID);
        SpiderFlow spiderFlow = spiderFlowService.getById(flowId);
        if (spiderFlow != null) {
            LOGGER.info("执行子流程:{}", spiderFlow.getName());
            SpiderNode root = SpiderFlowUtils.loadXMLFromString(spiderFlow.getXml());
            spider.executeNode(null, root, context, variables);
        } else {
            LOGGER.info("执行子流程:{}失败，找不到该子流程", flowId);
        }
    }

    @Override
    public String supportShape() {
        return "process";
    }

}
